package com.example.livedatademo.livedata;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: njb
 * @date: 2020/8/24 0024 23:02
 * @desc:
 */
public class TimerLiveDataViewModel extends ViewModel {
    // 不能传入Context 和含有不能传入Context引用对象，会造成内存泄漏
    private MutableLiveData<Integer> currentSecondLiveData;
    private int currentSecond;
    Timer timer;

    public MutableLiveData<Integer> getCurrentSecond() {
        if (currentSecondLiveData == null) {
            currentSecondLiveData = new MutableLiveData<>();
        }
        return currentSecondLiveData;
    }

    public void startTiming() {
        if (timer == null) {
            currentSecond = 0;
            timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    currentSecond++;
                    currentSecondLiveData.postValue(currentSecond);
                }
            };
            timer.schedule(timerTask, 1000, 1000);//延迟3秒执行
        }
    }

    /**
     * 由于屏幕旋转导致的Activity重建，该方法不会被调用
     * 只有ViewModel已经没有任何Activity与之有关联，系统则会调用该方法，你可以在此清理资源
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        timer.cancel();
    }
}
